//
//  TGPlanViewController.m
//  WanCaiC8
//
//  Created by QiuXun on 2019/1/16.
//  Copyright © 2019 tangang. All rights reserved.
//

#import "TGPlanViewController.h"
#import "PlanVC.h"
#import "LotteryNavTypeView.h"
#import "RankCell.h"
//#import "RankingTotalTopCollectionViewCell.h"
#import "InformationVM.h"
#import "HomePageVM.h"
#import "TGPlanCollectionViewCell.h"
#import "TGPlanTopCollectionViewCell.h"

#import "TGAdvertCollectionViewCell.h"
#import "TGAdvertCollectionReusableView.h"
#import "TGPlanRecommendHeadCollectionViewCell.h"
@interface TGPlanViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic ,strong) LotteryNavTypeView *lotteryNavTypeView;
@property (nonatomic ,strong) UICollectionView *collectionView;

@property (nonatomic ,assign)NSInteger   selectLottery;


@property (nonatomic ,strong)   PlanVC *planVC;

//开奖首页-彩种分类 不带时间
@property (nonatomic ,strong)NSMutableArray *lotteryList;
//记录 二级彩种分类 带倒计时
@property (nonatomic ,strong)NSMutableArray *secondLotteryList;

/**
 是否显示planVC
 */
@property (nonatomic ,assign)BOOL isShowPlan;
/**
 记录当前显示的六合彩期数
 */
@property (nonatomic ,copy)NSString *currentIssue;


@property (nonatomic ,strong)NSMutableArray *planArr;


@property (nonatomic ,strong) NSMutableArray *arr1;
@property (nonatomic ,strong) NSMutableArray *arr2;
@property (nonatomic ,strong) NSMutableArray *colArr1;
@property (nonatomic ,strong) NSMutableArray *colArr2;


@property (nonatomic ,strong) NSArray *navArr;


@end

@implementation TGPlanViewController

-(void)receiveNotification{
    NSLog(@"___________>接收到通知");
    LotteryTypeModel *model = self.navArr[self.selectLottery];
    [self getIndexLotteryListWithParentId:model.Id];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = @"彩票官方计划";
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification) name:@"TGReloadData" object:nil];
    
    
    self.planVC.view.hidden = YES;
    
    self.selectLottery = -1;
    
    
    [self setRightNavItem];

    [self.collectionView reloadData];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [self getNavLotteryTypeList];

        [self getNewIndexLotteryList];
        
        [self loadData];
        
        [self getAdvertising];
        
    });
    
   
}


#pragma mark -- 获取广告
- (void)getAdvertising{
    
    
    WS(weakSelf);
    
    self.arr1 = [NSMutableArray array];
    self.arr2 = [NSMutableArray array];
    self.colArr1 = [NSMutableArray array];
    self.colArr2 = [NSMutableArray array];

    [[InformationVM manage] getAdvertWithLocation:@"0" andType:9 Success:^(id returnValue) {
        
        for (AdvertisingModel *model in returnValue) {
            if (model.Layer == 1) {
                
                [weakSelf.arr1 addObject:model];
                
                if (model.IsDisplay) {
                    [weakSelf.colArr1 addObject:model];
                }
            }
            if (model.Layer == 2) {
                
                [weakSelf.arr2 addObject:model];
                if (model.IsDisplay) {
                    [weakSelf.colArr2 addObject:model];
                }
            }
        }
        
        
        [self insertAdvertising];
        
        
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
    //    }
}
#pragma mark - 插入广告 //
-(void)insertAdvertising{
    
    
    
    if (self.lotteryList.count>2&&self.arr2.count>0) {
        
        [self.lotteryList insertObject:self.arr2 atIndex:2];
    }
//    if (self.dataArr.count>6&&arr6.count>0) {
//        [self.dataArr insertObjects:arr6 atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(6, arr6.count)]];
//    }
    
    [self.collectionView reloadData];
    
}

#pragma mark --  获取二级彩种分类
-(void)getIndexLotteryListWithParentId:(NSString *)parentId{
    
    [SVProgressHUD show];
    [[HomePageVM manage] getHomeLotteryList:parentId andSuccess:^(id returnValue) {
        
        [self.secondLotteryList removeAllObjects];
        [self.secondLotteryList addObjectsFromArray:returnValue];
        
        [self.collectionView reloadData];
        [SVProgressHUD dismiss];
        
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
    
}
-(void)setRightNavItem{
    
    UIBarButtonItem *rightItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"nav_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(onclickNav)];
    self.navigationItem.rightBarButtonItem=rightItem;
    
}

#pragma mark -- 获取彩票导航分类
- (void)getNavLotteryTypeList{
    
        WS(weakSelf);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[HomePageVM manage] getLotteryTypeListWithParentId:@"0" Success:^(id returnValue) {
             
                self.navArr =[NSArray arrayWithArray:returnValue];
                
                if (self.navArr.count>0) {
                    
                    [self.lotteryNavTypeView setDataArr:self.navArr];
                    
                }
                
            } Fail:^(NSString *errorMessage, NSError *error) {
                
            }];
        });
    
}


#pragma mark --  获取新首页彩种信息列表
- (void)getNewIndexLotteryList{
    
    [[InformationVM manage] getNewIndexLotteryListSuccess:^(id returnValue) {
        
        self.lotteryList= [NSMutableArray arrayWithArray:returnValue];
        
    
        
    } andFail:^(NSString *errorMessage, NSError *error) {
        
    }];
}



#pragma mark - collectionView代理函数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    if (self.selectLottery == -1) {
        return 3;
    }else{
        return 1;
    }
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    if (self.selectLottery == -1) {
        
        if (section ==0) {
            return 1;
        }else if (section ==1){
            RecommendModel *rModel=self.planArr.firstObject;
            return rModel.arr.count +1;
        }
        else {
            
            return  self.lotteryList.count;
        }
        
    } else {
        
        return self.secondLotteryList.count;
        
    }
    
    
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.selectLottery == -1) {
        if (indexPath.section == 0) {
//            RankingTotalTopCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RankingTotalTopCollectionViewCell" forIndexPath:indexPath];
//
//
//            return cell;
//
            
            TGPlanRecommendHeadCollectionViewCell *cell =  [collectionView dequeueReusableCellWithReuseIdentifier:@"TGPlanRecommendHeadCollectionViewCell" forIndexPath:indexPath];
            return cell;
            
        } else if(indexPath.section == 2){
            if ([self.lotteryList[indexPath.row] isKindOfClass:[RankListModel class]]) {
                
                RankCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RankCell" forIndexPath:indexPath];
               
                RankListModel *model=self.lotteryList[indexPath.row];
                
                cell.model = model;
                
                return cell;
            }else{
                
                TGAdvertCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TGAdvertCollectionViewCell" forIndexPath:indexPath];
                cell.dataArr = self.lotteryList[indexPath.row];
                
                return cell;
                
            }
            
          
        }else{
            
            
            RecommendModel *rModel=self.planArr.firstObject;
            
            if (indexPath.row ==0) {
                TGPlanTopCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TGPlanTopCollectionViewCell" forIndexPath:indexPath];
                PlanRecommendModel *model=rModel.arr.lastObject;
                cell.count=[model.Num componentsSeparatedByString:@"|"].count+1.0;
                cell.model=rModel;
                
                return cell;
            }
            
            TGPlanCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TGPlanCollectionViewCell" forIndexPath:indexPath];
            
                cell.model=rModel.arr[indexPath.row-1];
            if (indexPath.row%2==0) {
                [cell setBgColor:[UIColor whiteColor]];
            }else{
                [cell setBgColor:DEFAULTBGCOLOR];
            }
            
            return cell;
            
            
        }
        
        
    }else {
        
        RankCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RankCell" forIndexPath:indexPath];
        
        cell.home_LotteryModel = self.secondLotteryList[indexPath.row];
        
        return cell;
        
        
    }
    

    
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (self.selectLottery == -1) {
        if (indexPath.section == 0) {
            return CGSizeMake(SCREEN_WIDTH, 115);
            
        } else if(indexPath.section == 2){
            if ([self.lotteryList[indexPath.row] isKindOfClass:[RankListModel class]]) {
                return CGSizeMake(SCREEN_WIDTH/2.0, SCREEN_WIDTH/5.0);
            }else{
                return CGSizeMake(SCREEN_WIDTH, 10+40*self.arr2.count-40*ceil(self.colArr2.count/2.0)+5);
            }
        }else{
//            if (indexPath.row == 0) {
                return CGSizeMake(SCREEN_WIDTH,70);
//            }
//            return CGSizeMake(SCREEN_WIDTH,50);

        }
        
    }else{
        
        return CGSizeMake(SCREEN_WIDTH/2.0, SCREEN_WIDTH/5.0);
        
    }
    
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section ==0 ||section ==2) {
        return CGSizeZero;
    }else{
        if (self.arr1.count) {
             return CGSizeMake(SCREEN_WIDTH, self.arr1.count*40-ceil(self.colArr1.count/2.0)*40+10);
        }else{
            return CGSizeZero;
        }
    }
    
}

- (UICollectionReusableView *) collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *reusableView = nil;
    
    if (kind == UICollectionElementKindSectionHeader)
    {
        if (indexPath.section ==1) {
            TGAdvertCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TGAdvertCollectionReusableView" forIndexPath:indexPath];
            if (self.arr1.count) {
                [headerView setAdModelArr:self.arr1 AndRowCount:(NSInteger)(self.arr1.count-ceil(self.colArr1.count/2.0))];
            }
            
            reusableView = headerView;
        }else{
            return nil;
        }
        
    }
    return reusableView;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.selectLottery == -1) {
        if (indexPath.section == 2) {
            
            if ([self.lotteryList[indexPath.row] isKindOfClass:[RankListModel class]]){
                
                
                RankListModel *model =  self.lotteryList[indexPath.row];
                NSArray *arr = self.navArr.copy;
                
                
                for (LotteryTypeModel *model in arr) {
                    NSLog(@"%@",model.lType);
                }
                
                NSInteger temp=0;
                for (int i= 0; i<arr.count; i++) {
                    
                    LotteryTypeModel *lotteryTypeModel = arr[i];
                    if ([model.BigLType integerValue] == [lotteryTypeModel.lType integerValue]) {
                        temp= i;
                    }
                }
                
                self.lotteryNavTypeView.isHomeEnter = YES;
                
                self.lotteryNavTypeView.selectLottery = temp;
                                
                self.title =[NSString stringWithFormat:@"%@官方计划",model.LTypeName];
                
                
                self.isShowPlan = YES;
                
                self.planVC.view.hidden = NO;
                
                LotteryTypeModel *lotteryTypeModel = arr[temp];
                lotteryTypeModel.lType = model.LType;
                
                self.planVC.lotteryModel = lotteryTypeModel;
                
            }
        }
        
        
    }
    else{


        Home_LotteryModel *model=self.secondLotteryList[indexPath.row];

        self.lotteryNavTypeView.isHomeEnter = YES;

        //        self.lotteryNavTypeView.selectLottery = temp;

        self.title =[NSString stringWithFormat:@"%@官方计划",model.LTypeName];
      
        self.isShowPlan = YES;

        self.planVC.view.hidden = NO;
        
        LotteryTypeModel *lotteryTypeModel = [LotteryTypeModel new];
        lotteryTypeModel.lType = model.LType;
        lotteryTypeModel.Name = model.LTypeName;
        
        self.planVC.lotteryModel = lotteryTypeModel;

    }

}

#pragma mark - 懒加载
- (LotteryNavTypeView *)lotteryNavTypeView{
    if (!_lotteryNavTypeView) {
        WS(weakSelf);
        _lotteryNavTypeView=[[LotteryNavTypeView alloc] init];

        
        _lotteryNavTypeView.chaneBlock = ^(NSInteger row) {
            
            weakSelf.selectLottery=row;
            
            if (row!=-1) {
                LotteryTypeModel *model = weakSelf.navArr[row];
                if (model.SonIdArr.count>1) {
  
                    weakSelf.title = [NSString stringWithFormat:@"%@官方计划",model.Name];
                    
                    weakSelf.isShowPlan = NO;

                    weakSelf.planVC.view.hidden = YES;
                   

                    [weakSelf getIndexLotteryListWithParentId:model.Id];
                    
                } else {
                    
                    weakSelf.title =[NSString stringWithFormat:@"%@官方计划",model.Name];
                   
                  
                    weakSelf.isShowPlan = YES;
                    weakSelf.planVC.view.hidden = NO;
                   
                    model.lType = model.SonIdArr.firstObject;
                    weakSelf.planVC.lotteryModel = model;

                }
                
            }else{
                
                weakSelf.title = @"彩票官方计划";
                weakSelf.isShowPlan = NO;
                weakSelf.planVC.view.hidden = YES;
         
                
                [weakSelf.collectionView reloadData];
            }
            
        };
        
        [self.view addSubview:_lotteryNavTypeView];
        [_lotteryNavTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(weakSelf.view);
            make.height.mas_equalTo(@40);
        }];
    }
    return _lotteryNavTypeView;
}

- (UICollectionView *)collectionView{
    if (_collectionView==nil) {
        WS(weakSelf);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        [layout setScrollDirection:UICollectionViewScrollDirectionVertical];
        layout.minimumInteritemSpacing = 0.0;
        layout.minimumLineSpacing = 0.0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor=[UIColor whiteColor];
        _collectionView.showsVerticalScrollIndicator=NO;
        
//        [_collectionView registerClass:[RankingTotalTopCollectionViewCell class] forCellWithReuseIdentifier:@"RankingTotalTopCollectionViewCell"];
//
         [_collectionView registerClass:[TGPlanRecommendHeadCollectionViewCell class] forCellWithReuseIdentifier:@"TGPlanRecommendHeadCollectionViewCell"];
        
        
        [_collectionView registerClass:[RankCell class] forCellWithReuseIdentifier:@"RankCell"];
        [_collectionView registerClass:[TGPlanCollectionViewCell class] forCellWithReuseIdentifier:@"TGPlanCollectionViewCell"];
        [_collectionView registerClass:[TGPlanTopCollectionViewCell class] forCellWithReuseIdentifier:@"TGPlanTopCollectionViewCell"];
 
        [_collectionView registerClass:[TGAdvertCollectionViewCell class] forCellWithReuseIdentifier:@"TGAdvertCollectionViewCell"];
        
        
        [_collectionView registerClass:[TGAdvertCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TGAdvertCollectionReusableView"];
        
        
        

        [self.view addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(weakSelf.view);
            make.top.equalTo(self.lotteryNavTypeView.mas_bottom);
        }];
        
        //        _collectionView.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //            weakSelf.page=1;
        //            [weakSelf.dataArr removeAllObjects];
        //            [weakSelf.tableView reloadData];
        //            [weakSelf getData];
        //        }];
        //        _tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        //            [weakSelf getData];
        //        }];
    }
    return _collectionView;
}
- (NSMutableArray *)secondLotteryList{
    if (!_secondLotteryList) {
        _secondLotteryList=[[NSMutableArray alloc]init];
    }
    return _secondLotteryList;
}



//第二个控制器

- (PlanVC *)planVC{
    if (!_planVC) {
        WS(weakSelf);
        _planVC=[[PlanVC alloc] init];
        [self.view insertSubview:_planVC.view aboveSubview:self.collectionView];
        [_planVC.view setFrame:CGRectMake(0, 40, SCREEN_WIDTH, SCREEN_HEIGHT-40)];
        [self addChildViewController:_planVC];
    }
    return _planVC;
}


- (NSMutableArray *)planArr{
    if (!_planArr) {
        
        _planArr = [NSMutableArray array];
    }
    return _planArr;
}



#pragma mark-获取六合彩计划 数据

- (void)loadData{

 
    [[BaseVM manage] GET_Field_Url:@"api/Plan/GetPlanData" Params:@{@"lType":@(5),@"pageIndex":@(1),@"pageSize":@(30)} successBlock:^(id returnValue) {
        
            if ([[returnValue objectForKey:@"Code"] intValue]==APIResponseStutusSuccess) {
            
            NSMutableArray *arr=[PlanRecommendModel mj_objectArrayWithKeyValuesArray:[[returnValue objectForKey:@"Data"] objectForKey:@"PageData"]].mutableCopy;

            self.planArr =[NSMutableArray array];
                
            for (int i=0; i<arr.count; i++) {


                PlanRecommendModel *model=  arr[i];
                if (model.Result ==nil) {[arr removeObject:model];}

            }
                
                
            PlanRecommendModel *tempModel=  arr.firstObject;
            for (int i=0; i<arr.count; i++) {

                PlanRecommendModel *model= arr[i];
                if ([model.Issue isEqualToString:tempModel.Issue]) {
                    [self.planArr addObject:model];
                }

            }
        


            if (arr.count>0) {
                [self.planArr removeAllObjects];
                [self createData:arr];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
//                if ([returnValue objectForKey:@"ExtraData"]!=nil) {
//                    [weakSelf.headView.lookNew setTitle:[NSString stringWithFormat:@"查看%@期%@计划",[returnValue objectForKey:@"ExtraData"],self.lotteryModel.lType] forState:UIControlStateNormal];
//                }
                
                
            });
            
            
        }else{
            [SVProgressHUD showErrorWithStatus:[returnValue objectForKey:@"Desc"]];
            //            fail(nil,nil);
        }
        
    } failBlock:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
        
        
    }];
    
    
}

- (void)createData:(NSArray *)arr{
  
    for (PlanRecommendModel *model in arr) {
        if ([model.ShowSort isEqualToString:@"龙虎"]) {
            continue;
        }
      
            if ([model.ShowSort isEqualToString:@"特尾大小"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"特尾大小"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"特合单双"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"四肖中特"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"十码中特"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"六不中"]) {
                continue;
            }
 

        if (model.OpenNum.length>0) {
            BOOL isHave =NO;
            for (RecommendModel *rModel in self.planArr) {
                if ([rModel.Issue isEqualToString:model.Issue]) {
                    isHave=YES;
                    [rModel.arr addObject:model];
                    break;
                }
            }
            if (!isHave) {
                RecommendModel *rModel=[[RecommendModel alloc]init];
                rModel.OpenTime=model.OpenTime;
                rModel.Issue=model.Issue;
                rModel.OpenNum=model.OpenNum;
                rModel.OpenNumAlias=model.OpenNumAlias;
                rModel.lType=model.lType;
                [rModel.arr addObject:model];
                [self.planArr addObject:rModel];
            }
        }
        
    }
    WS(weakSelf);
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.collectionView reloadData];
        
    });
    
}



- (void)dealloc
{
    
    NSLog(@"TGPlan   销毁");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"TGReloadData" object:self];
}

//
//-(void)viewDidDisappear:(BOOL)animated{
//    
//    [self.planVC cancleTimer];
//   
// 
//}


@end
